<template>
  <div>
    <el-dialog
      v-if="isOpen"
      class="dia-style"
      :title="title"
      :visible.sync="isOpen"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" @submit.native.prevent>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="产品版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入产品版本" maxlength="50" />
        </el-form-item>
        <el-form-item label="产品图标" prop="productPic">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :action="uploadUrl"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-exceed="haldleExceed"
            :file-list="fileListAdd"
            :limit="1"
            accept=".jpg,.png"
            :auto-upload="false"
            list-type="picture"
          >
            <!--               :http-request="httpRequest"   -->
            <el-button slot="trigger" size="small" type="primary">选取文件 </el-button>
            <div slot="tip" class="el-upload__tip">只能上传60*60像素的jpg/png文件，且只能上传一张，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="产品类型" prop="productCode">
          <div class="tabs-wk">
            <div
              v-for="(item, i) in tabsList"
              :key="i"
              :class="['tabs-list', selectedindex == i ? 'active' : '']"
              @click.prevent="handleCheck(i)"
            >
              {{ item.name }}
            </div>
          </div>
          <div v-if="tabsList.length" class="form-item-wk">
            <div
              v-for="(item, index) in tabsList[selectedindex].children"
              :key="index"
              :class="['form-item', currentIndex == index ? 'active' : '']"
              @click="handleClick(item, index)"
            >
              <div style="height:100px">
                <img :src="item.typeLogo || require('@/assets/images/import/jrcp01.png')" alt="">
              </div>

              <div :title="item.name">{{ !item.name?'':item.name.length>15?item.name.slice(0,15)+'...':item.name }}</div>
            </div>
            <span />
            <span />
            <span />
            <span />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <SelectDialog ref="selectRef" title="选择接入数据" />
  </div>
</template>

<script>
import SelectDialog from '../components/taskSelector'
import FileUpload from '@/components/FileUpload/index'
import { addProduct, editProduct } from '@/api/milkyway/accessProduct'

export default {
  name: 'EditProduct',
  components: { SelectDialog, FileUpload },
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    imgData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      // 二级标签索引值
      selectedindex: 0,
      tabsList: [],
      // 三级标签索引值
      currentIndex: null,
      isOpen: false,
      form: {},
      importProduct: [],
      // 表单参数
      rules: {
        productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
        productCode: [{ required: true, message: '请选择产品类型', trigger: 'blur' }]
      },
      fileListAdd: [],
      // uploadUrl:''
      uploadUrl: window.baseUrl.mlk + '/productinfo/productUpload'
    }
  },
  mounted() {
    this.tabsList = this.imgData
  },
  methods: {
    show(dataOption, formData) {
      this.isOpen = true
      this.reset()
      this.$nextTick(() => {
        this.form = formData
        if (formData && formData.parentId && this.tabsList.length > 0) {
          this.tabsList.forEach((item, index) => {
            if (item.id === formData.parentId) {
              this.selectedindex = index
            }
          })
          this.tabsList[this.selectedindex].children.forEach((item, i) => {
            if (item.id === formData.productCode) {
              this.currentIndex = i
            }
          })
        }

        if (formData.companyLogo) {
          this.fileListAdd = [{ url: formData.companyLogo }]
        }
        if (dataOption.length > 0) {
          this.tabsList = dataOption[0].children
        }
      })
    },
    // 自动调用httpRequest方法
    handleClick(data, i) {
      console.log(data, i)
      this.currentIndex = i
      this.form.productCode = data.id
    },
    handleSuccess(res, file, fileList) {
      this.form.companyLogo = res.data
      this.referForm()
    },
    haldleExceed(files, fileList) {
      if (fileList.length > 0) {
        this.$message.warning('只能上传一张文件，请删除重新选择')
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      if (!this.form.productCode) {
        this.form.productCode = null
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.fileListAdd.length) {
            if (!this.$refs.uploadRef.uploadFiles[0]) {
              return this.$message.error('请选择上传文件')
            }
            if (this.$refs.uploadRef.uploadFiles[0]?.status === 'ready') {
              this.$refs.uploadRef.submit()
            } else {
              this.form.companyLogo = this.form.companyLogo.slice(this.form.companyLogo.lastIndexOf('/') + 1)
              this.referForm()
            }
          } else {
            this.referForm()
          }
        } else {
          this.$message.error('请完善表单')
        }
      })
    },
    /* 表单提交接口 */
    referForm() {
      if (this.form.id != undefined) {
        editProduct(this.form).then((response) => {
          this.$modal.msgSuccess('修改成功')
          this.isOpen = false
          this.$refs.uploadRef.clearFiles()
          this.$emit('handleSubmit', this.form.productCode)
        })
      } else {
        addProduct(this.form).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.isOpen = false
          this.$refs.uploadRef.clearFiles()
          this.$emit('handleSubmit', this.form.productCode)
        })
      }
    },
    // 取消按钮
    cancel() {
      this.isOpen = false
      this.reset()
      this.$emit('changeOpen', false)
    },
    // 产品类型
    handleCheck(i) {
      this.selectedindex = i
      this.form.productCode = undefined
    },
    reset() {
      this.form = {
        productName: undefined,
        productCode: undefined,
        version: undefined
      }
      this.selectedindex = 0
      this.currentIndex = undefined
      this.fileListAdd = []
    },
    handleChange(file, fileList) {
      // 图片大小限制
      const isLt20M = file.size / 1024 < 500
      const isImg = file.raw.type == 'image/png' || file.raw.type == 'image/jpg' || file.raw.type == 'image/jpeg'
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 500kb!')
        fileList.splice(-1, 1)
      } else if (!isImg) {
        this.$message.error('上传jpg、png、jpeg格式的图片')
        fileList.splice(-1, 1)
      } else {
        this.fileListAdd = []
        this.fileListAdd = fileList
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}

.form-item-wk {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  align-items: stretch;
  text-align: center;

  span {
    width: 18%;
  }

  .form-item {
    margin-bottom: 20px;
    cursor: pointer;
    width: 18%;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;

    &.active {
      border: 1px solid #4b6eef;
    }

    &:hover {
      border: 1px solid #4b6eef;
    }

    img {
      width: 60px;
      display: block;
      margin: 20px auto;
    }

    div {
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0px 10px;
      line-height: 20px;
      vertical-align: center;
      margin: 0;
      border-top: 1px solid rgba(0, 0, 0, 0.15);
      overflow:hidden;
    }
  }
}

.tabs-wk {
  display: flex;
  flex-wrap: wrap;
  .tabs-list {
    border-bottom: 2px solid transparent;
    padding: 0 10px;
    margin-right: 4px;
    margin-bottom: 20px;
    cursor: pointer;
    white-space: nowrap;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;

    &.active {
      border-bottom: 2px solid #4b6eef;
    }
  }
}

::v-deep .el-dialog__body {
  //height: 70vh;
  overflow: auto;
}
</style>
